import 'package:flutter/material.dart';
import 'package:flutterdemo/0demo/database/model.dart';

import 'my_value_notifier.dart';

class ValueNotifierTestPage extends StatefulWidget {
  const ValueNotifierTestPage({Key key}) : super(key: key);

  @override
  State<ValueNotifierTestPage> createState() => _ValueNotifierTestPageState();
}

class _ValueNotifierTestPageState extends State<ValueNotifierTestPage> {
  ValueNotifier<Model> _valueNotifier = ValueNotifier(Model(iId: 0, name: "aa", age: 11));

  MyValueNotifier _myValueNotifier = MyValueNotifier();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("change notifier test"),
      ),
      body: Container(
        alignment: Alignment.center,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ValueListenableBuilder<Model>(
              valueListenable: _valueNotifier,
              builder: (context, value, child) {
                final Model value = _valueNotifier.value;
                return Text(value.toString());
              },
            ),
            ElevatedButton(
                onPressed: () {
                  // _valueNotifier.value.name = "change";
                  // _valueNotifier.value.iId = 1111;
                  // _valueNotifier.value.age = 2222;
                  // 上面这种方式没有改变引用地址，不行
                  _valueNotifier.value = Model(iId: 11, name: "change", age: 2222);
                },
                child: Text("change model")),
            ValueListenableBuilder(
              valueListenable: _myValueNotifier,
              builder: (context, value, child) {
                final List<Model> value = _myValueNotifier.value;
                return Text(value.isEmpty ? "hot reload refresh" : value.toString());
              },
            ),
            ElevatedButton(
              onPressed: () {
                _myValueNotifier.add(Model(iId: 1, name: "aa", age: 11));
              },
              child: Text("add"),
            ),
            ElevatedButton(
              onPressed: () {
                _myValueNotifier.removeAll();
              },
              child: Text("remove all"),
            ),
          ],
        ),
      ),
    );
  }
}
